<template>
  <div class="main app-container">
    <div class="main-container" ref="shipRef">
      <!--顶部查询表单-->
      <div class="searchBox">
        <div>
          <el-form label-position="right" :inline="true" ref="searchForm" size="mini" v-model="queryParam">
            <el-row v-for="(queryType, index) in queryTypeList" :key="index">
              <el-form-item label="条件一：">
                <el-select v-model="queryType.one" style="width: 150px" value-key="code" clearable filterable @change="queryTypeOneChange">
                  <el-option v-for="(item, index) in queryParamTypeOne" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                ：
                <el-input
                  v-if="!queryType.one.isDropDown"
                  clearable
                  v-model="queryParam[queryType.one.code]"
                  style="width: 250px"
                  placeholder="请输入"
                  :disabled="!queryType.one.code"
                ></el-input>
                <el-select
                  v-if="queryType.one.isDropDown"
                  v-model="queryParam[queryType.one.code]"
                  style="width: 250px"
                  clearable
                  filterable
                  multiple
                  :disabled="!queryType.one.code"
                >
                  <el-option v-for="(item, index) in queryType.one.list || []" :key="index" :label="item.name" :value="item.code">
                    <div v-if="queryType.one.code === 'brand'">
                      <span style="float: left; color: #8492a6; font-size: 13px">{{ item.name }}</span>
                      <span style="float: right">{{ item.brandDptName }}</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item style="margin: 0 10px">
                <el-button @click="addQueryCondition" icon="el-icon-circle-plus-outline" circle type="info"></el-button>
                <el-button @click="removeQueryCondition(index)" icon="el-icon-remove-outline" circle type="info"></el-button>
              </el-form-item>
              <el-form-item label="条件二：">
                <el-select v-model="queryType.two" style="width: 150px" value-key="startCode" clearable filterable @change="queryTypeTwoChange">
                  <el-option v-for="(item, index) in queryParamTypeTwo" :key="index" :label="item.name" :value="item"></el-option>
                </el-select>
                ：
                <el-date-picker
                  clearable
                  placeholder="选择开始时间"
                  style="width: 250px"
                  type="date"
                  v-model="queryParam[queryType.two.startCode]"
                  :disabled="!queryType.two.name"
                ></el-date-picker>
                -
                <el-date-picker
                  clearable
                  placeholder="选择结束时间"
                  style="width: 250px"
                  type="date"
                  v-model="queryParam[queryType.two.endCode]"
                  :disabled="!queryType.two.name"
                ></el-date-picker>
              </el-form-item>
            </el-row>
          </el-form>
        </div>
        <div>
          <el-button @click="searchList" size="mini" type="primary">查询</el-button>
          <el-button @click="clearQueryParam" size="mini" type="danger">清除</el-button>
        </div>
      </div>
      <div style="margin-top: 10px; margin-bottom: 10px">
        <buttonName @clickEvent="clickEvent"></buttonName>
      </div>
      <div>
        <el-form label-position="right" :inline="true" size="mini" v-model="statisticsForm">
          <el-form-item label="承接总吨数(吨)：">
            <el-input disabled maxlength="32" placeholder="" v-model="statisticsForm.transportTotal" size="mini" style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="发运总吨数(吨)：">
            <el-input disabled maxlength="32" placeholder="" v-model="statisticsForm.shipmentTotal" size="mini" style="width: 100px"></el-input>
          </el-form-item>
          <el-form-item label="未发运总吨数(吨)：">
            <el-input disabled maxlength="32" placeholder="" v-model="statisticsForm.noShipmentTotal" size="mini" style="width: 100px"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-table
          ref="multipleTable"
          :data="tableList"
          :height="tableHeight"
          border
          @row-click="rowClick"
          @selection-change="handleSelectionChange"
          :row-style="rowStyleHandler"
        >
          <el-table-column label="序号" type="index" width="55"></el-table-column>
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column align="center" label="合同号" prop="cmtContractNo" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="承接时间" prop="cmtSigningTime" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="装货时间" prop="loadingTime" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="卸货时间" prop="unloadingTime" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="司机姓名" prop="dvrName" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="车号" prop="trkNo" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="司机电话" prop="dvrPhone" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="价格" prop="price" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="吨数" prop="wabWeight" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="金额" prop="amount" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="品牌" prop="brandName" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="起运地" prop="wabPlaceof" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" label="目的地" prop="wabReceplace" show-overflow-tooltip width="200"></el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            :current-page="Pagination.currentPage"
            :layout="Pagination.layout"
            :page-size="Pagination.PageSize"
            :page-sizes="Pagination.pageSizeList"
            :total="Pagination.total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            background
            ref="pagination"
            small
          ></el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import paginationMixin from '@/mixins/pagination'
import isAuth from '@/mixins/buttonAuth'
import resizeMixin from '@/mixins/resize'
import buttonName from '@/components/buttonName/button-name'
import scrollChange from '@/utils/onscroll'
import { goodsBrandListA, queryWayShippingStatus } from '@/request/queryCensusP/shippingStatus'
import { queryDvrNameList, queryTrkNoList } from '@/request/dropDown'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import store from '@/store'

export default {
  mixins: [isAuth, paginationMixin, resizeMixin],
  name: 'shippingStatus',
  data() {
    return {
      currentRole: (localStorage.getItem('IS_SHOW1') || '').toString(), // 当前角色
      statisticsForm: {
        transportTotal: 0,
        shipmentTotal: 0,
        noShipmentTotal: 0,
      },
      tableList: [],
      selectedList: [],
      tableHeight: 200,
      // 查询项目下拉 第一组
      queryParamTypeOne: [
        {
          name: '合同号',
          code: 'contractNo',
        },
        {
          name: '起运地',
          code: 'wabPlaceof',
        },
        {
          name: '目的地',
          code: 'wabReceplace',
        },
        {
          name: '车牌号',
          code: 'trkNos',
          isDropDown: true,
          list: [],
        },
        {
          name: '司机',
          code: 'drvNames',
          isDropDown: true,
          list: [],
        },
        {
          name: '品牌',
          code: 'brands',
          isDropDown: true,
          list: [],
        },
      ],
      // 查询项目下拉 第二组
      queryParamTypeTwo: [
        {
          name: '承接时间',
          startCode: 'cmtSigningTimeStart',
          endCode: 'cmtSigningTimeEnd',
        },
        {
          name: '装货时间',
          startCode: 'loadStartTime',
          endCode: 'loadEndTime',
        },
        {
          name: '卸货时间',
          startCode: 'unloadStartTime',
          endCode: 'unloadEndTime',
        },
      ],
      currentQueryTypeOne: {
        name: '',
        brandDptName: '',
        code: '',
        isDropDown: false,
        list: [],
      },
      currentQueryTypeTwo: {
        name: '',
        startCode: '',
        endCode: '',
      },
      queryParam: {
        contractNo: '', // 委托书编号
        brand: '', // 品牌
        trkNo: '', // 车牌号
        drvName: '', // 司机姓名
        cmtSigningTimeStart: undefined, // 承接开始时间
        cmtSigningTimeEnd: undefined, // 承接结束时间
        loadStartTime: undefined, // 装货开始时间
        loadEndTime: undefined, // 装货结束时间
        unloadStartTime: undefined, // 卸货开始时间
        unloadEndTime: undefined, // 卸货开始时间
      },
      header_name: ['合同号', '承接时间', '装货时间', '卸货时间', '司机姓名', '车号', '司机电话', '价格', '吨数', '金额', '品牌', '起运地', '目的地'],
      header: [
        'cmtContractNo',
        'cmtSigningTime',
        'loadingTime',
        'unloadingTime',
        'dvrName',
        'trkNo',
        'dvrPhone',
        'price',
        'wabWeight',
        'amount',
        'brandName',
        'wabPlaceof',
        'wabReceplace',
      ],
      queryTypeList: [
        {
          one: {
            name: '',
            brandDptName: '',
            code: '',
            isDropDown: false,
            list: [],
          },
          two: {
            name: '',
            startCode: '',
            endCode: '',
          },
        },
      ],
    }
  },
  created() {
    this.resize = () => {
      this.tableHeight = this.$refs.shipRef.offsetHeight - 175
    }
  },
  components: {
    buttonName,
  },
  mounted() {
    scrollChange(document.querySelector('#ship-table .el-table__body-wrapper'))
    this.refreshList()
    this.initBrandList()
    this.initDrvList()
    this.initTrkList()
  },
  methods: {
    rowStyleHandler({ row }) {
      if (this.selectedList.includes(row)) {
        return {
          background: '#5786ee',
        }
      }
    },
    getList() {
      if (['3', '6'].includes(this.currentRole)) {
        this.queryParam.client = this.$store.state.user.DPTID_DX_H
      }
      // 集团
      if (this.currentRole === '2') {
        this.queryParam.upperClient = store.state.user.DPTID_DX_H
      }
      queryWayShippingStatus(
        Object.assign(
          {
            index: this.Pagination.currentPage,
            size: this.Pagination.pageSize,
          },
          this.queryParam
        )
      ).then(res => {
        this.tableList = res.data.data
        this.statisticsForm = res.data
        this.updatePaginationTotal(res.total)
      })
    },
    initBrandList() {
      goodsBrandListA({}).then(res => {
        for (let val of this.queryParamTypeOne) {
          if ('brands' === val.code) {
            for (let item of res.data) {
              val.list.push({
                name: item.brandName,
                brandDptName: item.dptName,
                code: item.brandCode,
              })
            }
            break
          }
        }
      })
    },
    initDrvList() {
      queryDvrNameList().then(res => {
        for (let val of this.queryParamTypeOne) {
          if ('drvNames' === val.code) {
            for (let item of res.data) {
              val.list.push({
                name: item.dvrName,
                code: item.dvrId,
              })
            }
            break
          }
        }
      })
    },
    initTrkList() {
      queryTrkNoList().then(res => {
        for (let val of this.queryParamTypeOne) {
          if ('trkNos' === val.code) {
            for (let item of res.data) {
              val.list.push({
                name: item.trkNo,
                code: item.trkId,
              })
            }
            break
          }
        }
      })
    },
    clickEvent({ mdlCode }) {
      if (mdlCode === 'export') {
        this.exportExcel()
      }
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    rowClick(value) {
      this.$refs['multipleTable'].toggleRowSelection(value)
    },
    queryTypeOneChange() {
      const codes = this.queryTypeList.map(item => item.one.code)
      for (let key of Object.keys(this.queryParam)) {
        if (!codes.includes(key) && key.toLowerCase().indexOf('start') === -1 && key.toLowerCase().indexOf('end') === -1) {
          this.queryParam[key] = ''
        }
      }
      // this.queryParam.contractNo = '' // 委托书编号
      // this.queryParam.brand = '' // 品牌
      // this.queryParam.trkNo = '' // 车牌号
      // this.queryParam.drvName = '' // 司机姓名
    },
    queryTypeTwoChange() {
      const startCodes = this.queryTypeList.map(item => item.two.startCode)
      const endCodes = this.queryTypeList.map(item => item.two.endCode)
      for (let key of Object.keys(this.queryParam)) {
        if (!startCodes.includes(key) && !endCodes.includes(key) && key.toLowerCase().indexOf('start') !== -1 && key.toLowerCase().indexOf('end') !== -1) {
          this.queryParam[key] = undefined
        }
      }
      // this.queryParam.cmtSigningTimeEnd = undefined
      // this.queryParam.cmtSigningTimeStart = undefined
      // this.queryParam.loadStartTime = undefined // 装货开始时间
      // this.queryParam.loadEndTime = undefined // 装货结束时间
      // this.queryParam.unloadStartTime = undefined // 卸货开始时间
      // this.queryParam.unloadEndTime = undefined // 卸货开始时间
    },
    clearQueryParam() {
      this.queryTypeOneChange()
      this.queryTypeTwoChange()
      this.currentQueryTypeOne = {
        name: '',
        brandDptName: '',
        code: '',
        isDropDown: false,
        list: [],
      }
      this.currentQueryTypeTwo = {
        name: '',
        startCode: '',
        endCode: '',
      }
    },
    exportExcel() {
      const nos = []
      const wayIds = []
      if (this.selectedList.length) {
        for (let item of this.selectedList) {
          if (item.wayId) {
            wayIds.push(item.wayId)
          } else {
            nos.push(item.cmtContractNo)
          }
        }
      }
      queryWayShippingStatus(
        Object.assign(
          {
            index: -1,
            size: this.Pagination.pageSize,
          },
          this.queryParam,
          { wayIds, nos }
        )
      ).then(res => {
        if (res.data.length) {
          export_json_to_excel({
            header: this.header_name,
            filename: '陆运情况汇总',
            data: res.data.map(v => this.header.map(x => v[x])),
          })
        } else {
          this.$message.info('未找到数据')
        }
      })
    },
    removeQueryCondition(index) {
      if (index !== 0) {
        this.queryTypeList.splice(index, 1)
      }
    },
    addQueryCondition() {
      this.queryTypeList.push({
        one: {
          name: '',
          brandDptName: '',
          code: '',
          isDropDown: false,
          list: [],
        },
        two: {
          name: '',
          startCode: '',
          endCode: '',
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.main {
  .main-container {
    width: 100%;
    height: 100%;
    .searchBox {
      display: flex;
    }
  }
}
</style>
